{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# bin_packing_sat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/sat/bin_packing_sat.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/ortools/sat/samples/bin_packing_sat.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "Solves a simple bin packing problem using CP-SAT.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import io\n",
    "\n",
    "import pandas as pd\n",
    "\n",
    "from ortools.sat.python import cp_model\n",
    "\n",
    "\n",
    "def create_data_model() -> tuple[pd.DataFrame, pd.DataFrame]:\n",
    "    \"\"\"Create the data for the example.\"\"\"\n",
    "\n",
    "    items_str = \"\"\"\n",
    "  item  weight\n",
    "    i1      48\n",
    "    i2      30\n",
    "    i3      19\n",
    "    i4      36\n",
    "    i5      36\n",
    "    i6      27\n",
    "    i7      42\n",
    "    i8      42\n",
    "    i9      36\n",
    "   i10      24\n",
    "   i11      30\n",
    "  \"\"\"\n",
    "\n",
    "    bins_str = \"\"\"\n",
    "  bin  capacity\n",
    "   b1       100\n",
    "   b2       100\n",
    "   b3       100\n",
    "   b4       100\n",
    "   b5       100\n",
    "   b6       100\n",
    "   b7       100\n",
    "  \"\"\"\n",
    "\n",
    "    items = pd.read_table(io.StringIO(items_str), index_col=0, sep=r\"\\s+\")\n",
    "    bins = pd.read_table(io.StringIO(bins_str), index_col=0, sep=r\"\\s+\")\n",
    "    return items, bins\n",
    "\n",
    "\n",
    "def main() -> None:\n",
    "    items, bins = create_data_model()\n",
    "\n",
    "    # Create the model.\n",
    "    model = cp_model.CpModel()\n",
    "\n",
    "    # Variables\n",
    "    # x[i, j] = 1 if item i is packed in bin j.\n",
    "    items_x_bins = pd.MultiIndex.from_product(\n",
    "        [items.index, bins.index], names=[\"item\", \"bin\"]\n",
    "    )\n",
    "    x = model.new_bool_var_series(name=\"x\", index=items_x_bins)\n",
    "\n",
    "    # y[j] = 1 if bin j is used.\n",
    "    y = model.new_bool_var_series(name=\"y\", index=bins.index)\n",
    "\n",
    "    # Constraints\n",
    "    # Each item must be in exactly one bin.\n",
    "    for unused_name, all_copies in x.groupby(\"item\"):\n",
    "        model.add_exactly_one(x[all_copies.index])\n",
    "\n",
    "    # The amount packed in each bin cannot exceed its capacity.\n",
    "    for selected_bin in bins.index:\n",
    "        items_in_bin = x.xs(selected_bin, level=\"bin\")\n",
    "        model.add(\n",
    "            items_in_bin.dot(items.weight)\n",
    "            <= bins.loc[selected_bin].capacity * y[selected_bin]\n",
    "        )\n",
    "\n",
    "    # Objective: minimize the number of bins used.\n",
    "    model.minimize(y.sum())\n",
    "\n",
    "    # Create the solver and solve the model.\n",
    "    solver = cp_model.CpSolver()\n",
    "    status = solver.solve(model)\n",
    "\n",
    "    if status == cp_model.OPTIMAL or status == cp_model.FEASIBLE:\n",
    "        print(f\"Number of bins used = {solver.objective_value}\")\n",
    "\n",
    "        x_values = solver.boolean_values(x)\n",
    "        y_values = solver.boolean_values(y)\n",
    "        active_bins = y_values.loc[lambda x: x].index\n",
    "\n",
    "        for b in active_bins:\n",
    "            print(f\"Bin {b}\")\n",
    "            items_in_active_bin = x_values.xs(b, level=\"bin\").loc[lambda x: x].index\n",
    "            for item in items_in_active_bin:\n",
    "                print(f\"  Item {item} - weight {items.loc[item].weight}\")\n",
    "            print(\n",
    "                \"  Packed items weight:\"\n",
    "                f\" {items.loc[items_in_active_bin].sum().to_string()}\"\n",
    "            )\n",
    "            print()\n",
    "\n",
    "        print(f\"Total packed weight: {items.weight.sum()}\")\n",
    "        print()\n",
    "        print(f\"Time = {solver.wall_time} seconds\")\n",
    "    elif status == cp_model.INFEASIBLE:\n",
    "        print(\"No solution found\")\n",
    "    else:\n",
    "        print(\"Something is wrong, check the status and the log of the solve\")\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
